<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAddRole">创建角色</el-button>

    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" stripe>
      <el-table-column 
        prop="name" 
        align="center" 
        label="角色名称">
      </el-table-column>
      <el-table-column 
        prop="description" 
        align="center" 
        label="描述">
      </el-table-column>
      <el-table-column 
        prop="adminCount" 
        align="center" 
        label="管理员数">
      </el-table-column>
      <el-table-column 
        prop="createat" 
        align="center" 
        label="创建时间">
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleMenu(scope)">分配菜单</el-button>
          <el-button type="text" size="small" @click="handleResource(scope)">分配权限</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDetail(scope)">详情</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建/编辑角色 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'新建角色'">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="角色名称">
          <el-input v-model="role.name" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="role.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="描述"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>

    <!-- 分配菜单权限 -->
    <el-dialog :visible.sync="menuDialogVisible" title="分配菜单权限">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="角色名称">
          <el-input v-model="role.name" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="菜单">
          <el-tree
            :data="menus"
            show-checkbox
            node-key="id"
            ref="menuTree"
            :default-expanded-keys="[]"
            :default-checked-keys="[]"
            :props="defaultProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="menuDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmMenu">确认</el-button>
      </div>
    </el-dialog>

    <!-- 分配资源权限 -->
    <el-dialog :visible.sync="resourceDialogVisible" title="分配资源权限">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="角色名称">
          <el-input v-model="role.name" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="资源">

        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="resourceDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmResource">确认</el-button>
      </div>
    </el-dialog>

    <!-- 角色详情 -->
    <el-dialog :visible.sync="detailDialogVisible" title="角色详情">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="角色名称">
          {{ roleDetail.role.name }}
        </el-form-item>
      </el-form>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>菜单权限</span>
        </div>
        <div class="text item">
          <el-row>
            <el-col :span="20"><div class="grid-content"><el-tag v-for="menu in roleDetail.menus" :key="menu.title">{{ menu.title }}</el-tag></div></el-col>
          </el-row>
        </div>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>资源权限</span>
        </div>
        <div class="text item">
          <el-row>
            <el-col :span="20"><div class="grid-content"><el-tag v-for="resource in roleDetail.resources" :key="resource.name">{{ resource.name }}</el-tag></div></el-col>
          </el-row>
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { getRoles, addRole, delRole, updateRole, getDetail } from '@/api/role'
import { getMenus } from '@/api/permission'

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  data() {
    return {
      role: {
        id: '',
        name: '',
        description: ''
      },
      menus: [],
      resources: [],
      rolesList: [],
      roleDetail: {
        role: '',
        menus: [],
        resources: []
      },
      dialogVisible: false,
      menuDialogVisible: false,
      resourceDialogVisible: false,
      detailDialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getMenus()
    this.getRoles()
  },
  methods: {
    async getMenus() {
      const res = await getMenus()
      this.serviceRoutes = res.data
      this.routes = this.generateRoutes(res.data)
    },
    async getRoles() {
      const res = await getRoles()
      this.rolesList = res.data
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddRole() {
      this.role = {}
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      const role = scope.row
      this.role.id = role.id
      this.role.name = role.name
      this.role.description = role.description

      this.dialogType = 'edit'
      this.dialogVisible = true

    },
    handleMenu(scope) {

      this.menuDialogVisible = true


    },
    handleResource(scope) {

      this.resourceDialogVisible = true
    },
    async handleDetail(scope) {
      const res = await getDetail(scope.row.id)
      console.log("Admin Detail", res)
      this.roleDetail = res.data
      this.detailDialogVisible = true

    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'

      if (isEdit) {
        const res =  await updateRole(this.role).then(() => {
          this.$message({
            type: 'success',
            message: '更新角色成功!'
          });
        })
      } else {
        const res =  await addRole(this.role).then(() => {
          this.$message({
            type: 'success',
            message: '创建角色成功!'
          });
        })
      }

      this.getRoles()
      this.dialogVisible = false

    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    },
    handleDelete(id) {
      console.log("id",id)
      this.$confirm('确认删除此角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delRole(id).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })

        this.getRoles()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
